
/*eslint-disable */
import Vue from 'vue';
import Router from 'vue-router';
import { requestData } from '@/api';
import { getPublicPath } from '@/utils/publicPath';
import { getUrlParams } from '@/utils/common';
const { menuid } = getUrlParams();
import NProgress from 'nprogress';
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false });
Vue.use(Router);
/**
 * 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
 * @param {*} file 菜单路径
 * @param {*} module 项目模块名称 默认当前系统模块
 */
const _import = require('./import-' + process.env.NODE_ENV);
// 全局路由
const globalRoutes = [
  {
    path: '/login',
    component: resolve => require(['../pages/login'], resolve)
  }, 
  {
    path: '/404',
    component: resolve => require(['@/components/404'], resolve)
  }
];
const mainRoutes = {
  path: '/',
  component: resolve => require(['../pages/layout'], resolve),
  name: 'main',
  children: [
    { path: '/home', component: _import('/home'), name: 'home',  meta: { title: 'demo-echarts', isTab: true }},
    { path: '/task', component: _import('/task'), name: 'task', meta: { title: '任务管理', isTab: true }},
    {
      path: '/monitor-data',
      name: 'monitor-data',
      component: _import('/monitor-data'),
      meta:{
        title: '应急监测数据',
        isTab:true
      }
    }, 
    {
      path: '/equip-status',
      name: 'equip-status',
      component: _import('/equip-status'),
      meta:{
        title: '设备状态',
        isTab:true
      }
    }, 
    {
      path: '/map',
      name:'map',
      component: _import('/map'),
      meta:{
        title: '一张图',
        isTab:true
      }
    }, 
    {
      path: '/video',
      name:'video',
      component: _import('/video'),
      meta:{
        title: '车载视频监控',
        isTab:true
      }
    }, 
    {
      path: '/video-back',
      name:'video-back',
      component: _import('/video-back'),
      meta:{
        title: '车载历史视频',
        isTab:true
      }
    }, 
    {
      path: '/remote-control',
      name:'remote-control',
      component: _import('/remote-control'),
      meta:{
        title: '远程控制',
        isTab:true
      }
    }, 
    {
      name: 'redirect',
      path: '/redirect',
      component: resolve => require(['@/components/redirect'], resolve)
    }
  ],
  beforeEnter(to, from, next) {
    const token = Vue.cookie.get('token');
    if (!token || !/\S/.test(token)) {
      // clearLoginInfo();
      // window.location.href = getPublicPath() + 'system/index.html#/login';
    }
    next();
  }
};

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
});

router.beforeEach((to, from, next) => {
  next();
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  // if (router.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
  //   next();
  // } else {
  //   requestData({
  //     url: '/service-base/button/userButtonList',
  //     type: 'get',
  //     params: {
  //       // isapp: 0 //  只查平台菜单
  //       child: 1,
  //       menuid: menuid
  //     }
  //   }).then(resp => {
  //     const { data, success } = resp;
  //     if (success) {
  //       const menuList = data.data;
  //       fnAddDynamicMenuRoutes(menuList);
  //       router.options.isAddDynamicMenuRoutes = true;
  //       sessionStorage.setItem('menuList', JSON.stringify(menuList || '[]'));
  //       next({ ...to, replace: true });
  //     } else {
  //       sessionStorage.setItem('menuList', '[]');
  //       next();
  //     }
  //   }).catch((e) => {
  //     console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue');
  //     window.location.href = getPublicPath() + 'system/index.html#/login';
  //   });
  // }
});

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = [];
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global';
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children);
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main';
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children);
    } else if (menuList[i].menuurl) {
      var route = {
        path: '',
        component: '',
        name: menuList[i].menuname,
        meta: {
          systemcode: menuList[i].systemcode,
          buttonList: menuList[i].buttonList,
          menuId: menuList[i].menuid,
          title: menuList[i].menuname,
          isDynamic: true
          // isTab: true,
        }
      };
      route.path = menuList[i].menuurl.split('?')[0];
      route.component = null;
      try {
        route['component'] = _import(`${menuList[i].menuurl.split('?')[0]}`, menuList[i].systemcode) || null;
      } catch (e) {
        console.log(e);
      }

      routes.push(route);
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes);
  } else {
    mainRoutes.name = 'main-dynamic';
    mainRoutes.children = routes;
    router.addRoutes([
      mainRoutes,
      { path: '*', redirect: '/404', hidden: true }
    ]);
    console.log('\n');
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue');
    console.log(mainRoutes.children);
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue');
  }
}

router.afterEach(transition => {
  NProgress.done(true);
});

export default router;
